package stu.aistar.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import stu.aistar.dao.ISeatsDao;
import stu.aistar.dao.ISessionDao;
import stu.aistar.dao.IUserDao;
import stu.aistar.model.pojo.*;
import stu.aistar.model.vo.SeatVo;
import stu.aistar.service.ISeatsService;
import stu.aistar.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private UserService userService;

    @Autowired
    private IUserDao userDao;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    private SeatVo seatVos;
    private List<Seats> seatsList;

    @Autowired
    private ISeatsService seatsService;
    @Autowired
    private ISeatsDao seatsDao;
    @Autowired
    private ISessionDao sessionDao;
    @GetMapping("/hello")
    @ResponseBody
    public Result hello(){
        return new Result("300","hellowordsuccess",null);
    }

    @GetMapping("/hello2")
    @ResponseBody
    public Result hello2(String username,Integer age){
        System.out.println("username:"+username);
        System.out.println("age:"+age);
        return new Result("200","helloword体验成功",null);
    }

    @GetMapping("/index")
    public String index(){
        //return "/WEB-INF/404.jsp";
        return "index";
    }

    @GetMapping("/index2")
    public String index2(){
        //return "/WEB-INF/404.jsp";
        return "index-2";
    }

    @GetMapping("/moviecheckout")
    public String movieCheckout(){
        //return "/WEB-INF/404.jsp";
        return "movie-checkout";
    }
    @GetMapping("/moviedetails")
    public String movieDetails(){
        //return "/WEB-INF/404.jsp";
        return "movie-details";
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "sign-in";

    }
    @GetMapping("/register")
    public  String toRegister(){
        return "sign-up";
    }

    @RequestMapping("/isExistPhone")
    @ResponseBody
    public Result isExistPhone(@RequestParam("phone") String phone){
        Result result = null;
        User user = userService.findUserByPhone(phone);
        if(null == user){
            result = new Result("200","手机号未被注册",null);
        }else {
            result = new Result("404","手机已被注册",null);
        }
        return result;
    }

    @PostMapping("/sendCode")
    @ResponseBody
    public Result getCode(@RequestParam("phone") String phoneNumber, HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        map.put("apiUrl", "https://sms_developer.zhenzikj.com");
        map.put("appId", "108895");
        map.put("appSecret", "f54e290e-b61b-422a-bd04-430e679b5f4b");
        map.put("templateId", "4993");
        map.put("timeOut", "1");
        try {
            String code = userService.sendVerifyCode(phoneNumber, 6, map);
            // 将验证码存入redis缓存中,时效60s
            redisTemplate.opsForValue().set(phoneNumber + "_code", code, 60, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("phone", phoneNumber, 60, TimeUnit.SECONDS);
            return new Result("200", "发送成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", e.getMessage(), null);
        }
    }

    @RequestMapping("/registerUser")
    @ResponseBody
    public Result register(HttpServletRequest request,@RequestParam("phone")String phone,@RequestParam("password") String password,@RequestParam("code")String code){
        Result result = null;
        //获取生成的验证码
        String send_code = redisTemplate.opsForValue().get(phone + "_code");
        String recv_phone = redisTemplate.opsForValue().get("phone");

        //encoder经过SHA-256 +随机盐+密钥对密码进行加密**[不可逆]的结果
        String encoder= bCryptPasswordEncoder.encode(password);
        if(code.equals(send_code)&&phone.equals(recv_phone)){
            result = new Result("200","验证码正确",null);
            //用户注册
            userService.registUser(phone, encoder);
        }else if(null == send_code){
            //验证码过期
            result = new Result("404","验证码失效",null);
        }else{
            result = new Result("500","验证码错误",null);
        }

        return result;
    }
    @PostMapping("/login")
    @ResponseBody
    public Result login(User user,HttpServletRequest request){
        Result result = null;
        User user1=userDao.findUserByPhone(user.getPhone());
        if(null!=user1){
            boolean flag = bCryptPasswordEncoder.matches(user.getPassword(),user1.getPassword());
            if(flag){
                request.getSession().setAttribute("user",user);
                System.out.println(request.getSession().getAttribute("user"));
                redisTemplate.opsForValue().set("user_"+user.getPhone(), String.valueOf(user1));
                result = new Result("200","登录成功",null);
            }else{
                result = new Result("404","手机号或密码错误",null);
            }
        }else{
            result = new Result("404","手机号或密码错误",null);
        }

        return result;
    }
    @RequestMapping("/index")
    public String index3(){
        return "index";
    }

    //1 生成支付宝二维码扫码登录
    @GetMapping("alipayLogin")
    public String zfb() {
        String appid = "2021000117630004";
        String redirect_uri = "http://localhost:8008/boot/user/callback";//扫描成功后回调地址
        try {
            redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?app_id=" + appid + "&scope=auth_user&redirect_uri=" + redirect_uri;
        return "redirect:"+url;
    }

    @GetMapping("callback")
    public String callback(@RequestParam("app_id") String APP_ID, @RequestParam("auth_code") String code) throws AlipayApiException {
        String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAguOzUw/UMelmfqqCkSTxye+FAOYDjo9Jh0SPBOsbr/NfKxRq+DkJ+Rh35h7iVMoPGQ/YwihKrIWbu0TKi/p2+2WFUCwH1D1V2Hx0YIoQozfwR4Hyaifk8k1s8zmncvfEKSa0DQGDTfwFRYYRjeMaYdrJofBXknvz/kfTVTiUyASMR3uPUpoRNI0HTzO+iphGc8Awl/cpK9IHkHKcrRrsowzgR6iVnc803rYc/kMUFNkhmQHhSlXdTrUTaFwMSAchA4HCPabx7LOCq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oXzefi0N4/gI5E8c2VfRtLn8m74zOchXr7c35ELzAiPTRitLNOKfkUV2q4V59FWNKm/WYQuiypkAfNaFyRk68Y8XnhoZWPrR6D0sdgLLl/yiHqKeEOJ28c3UYva9P4UIiB1kR1QKBgQCe0wAtCPVLa9lt04E+ELZDD6nFLVXo0BmNs5idJengruWubSdbc0O9rgn9T1Q0U2ByhRLaURil2k+vXXdkdda1ptTCz5bnMFisyV0aO368Wnh6ii6N4yl4ZfRN9Tj1W0jNopuL5LGEvGxi1LPswRpFxNTtbXKxBCdL56rQUzHiEQKBgHgDi3YR2Af/0g5v4UuYK5Svck6MPBi4x47gYfU8ogbf0wJlSAB7FeVEYkl0hzIG2ep2hxe7Xsm/h0nw/0sKU3CPLBdJIGY9SDBXX6WFHpanuPIIghWdRwZNpI3mBDTHv2uVtdWOAg4mF6g02yuCs8QXjyOfbw4giUmmCkXdY4g1AoGBANrdcRyIB0038v0JIsB5C+PCUSrBJw63J7uEihf4pVKQzTM7oCefoHC2kmfpT6NcG3x1NjT/15nEnbgUyv6XmETXuVRgUtL6QKxMo9z9MfJ9TQUYdnhJk33eYY7CzfYnsekHY/sxtgsFTwqz07jSVAXjy1LLJjievqkwc+6/A3Bb";

        String CHARSET = "utf-8";
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        AlipayUserInfoShareRequest userrequest = new AlipayUserInfoShareRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            String accessToken = oauthTokenResponse.getAccessToken();
            AlipayUserInfoShareResponse userinfo = alipayClient.execute(userrequest, accessToken);
            String nickName = userinfo.getNickName();
            String openid = userinfo.getUserId();

            User user=new User();
            user.setName(nickName);
            user.setPhone(openid);
            user.setPassword(openid);
            System.out.println("nickName:"+nickName);
            System.out.println("openid:"+openid);
            User loginUser = userService.login(openid,openid);
            if (null == loginUser){
                System.out.println("登录失败");
                return "redirect:/user/toLogin";
            }else {
                //将用户信息存放到redis中
                redisTemplate.opsForValue().set("user_"+openid, String.valueOf(user));

                System.out.println("登录成功");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "redirect:/index/movie";
    }

    /**
     * 分页查询+条件查询
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/admin/getUserInfo")
    @ResponseBody
    public Map<String,Object> getUserInfo(HttpServletRequest request){
        String page = request.getParameter("page");
        String pageSize = request.getParameter("limit");
        String params = request.getParameter("searchParams");
        String name = null;
        String username=null;
        String phone=null;
        //先转换成JSONObject类型
        if (null != params){
            JSONObject obj = JSONObject.parseObject(params);
            name= obj.getString("name");
            username = obj.getString("username");
            phone = obj.getString("phone");
        }
        Map<String,Object> userMap = new HashMap<String, Object>();
        PageInfo<User> users = userService.findUsersByPage(page,pageSize,username,phone,name);
        for (User user : users.getList()) {
            System.out.println(user);
        }
        userMap.put("code",0);
        userMap.put("msg","查找成功");
        //数据总数
        userMap.put("count",users.getTotal());
        userMap.put("data",users.getList());
        return userMap;
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @RequestMapping("/admin/delUserById")
    @ResponseBody
    public Result delUserById(@RequestParam("id") Integer id){
        int row = userService.delUserById(id);
        Result result = null;
        if (row == 0){
            result = new Result("500","删除失败","");
        }else {
            result = new Result("200","删除成功","");
        }
        return result;
    }


    @RequestMapping("/admin/editUser")
    @ResponseBody
    public Result updateUser(@RequestBody User user){
        System.out.println("================================================");
        System.out.println(user.toString());
        int row = userService.updateUser(user);
        Result result = null;
        if (row == 0){
            result = new Result("500","修改失败","");
        }else {
            result = new Result("200","修改成功","");
            System.out.println(result);
        }
        return result;
    }
}
